package com.mf.all.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import static com.mf.all.constant.ConstantBasic.*;

import com.mf.all.exception.GraceException;
import com.mf.all.service.ServiceDept;
import com.mf.all.service.ServiceUser;
import com.mf.all.utils.UtilIdGenerator;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.mf.all.entity.dto.DtoJob;
import com.mf.all.entity.req.search.SearchReqJob;
import com.mf.all.mapper.MapperJob;
import com.mf.all.service.ServiceJob;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class ImplServiceJob extends ServiceImpl<MapperJob, DtoJob> implements ServiceJob {
    @Resource
    private ServiceDept serviceDept;

    @Resource
    private ServiceUser serviceUser;


    @Override
    public LambdaQueryWrapper<DtoJob> fillParams(SearchReqJob params) {
        final LambdaQueryWrapper<DtoJob> wrapper = loadQw();
        if(StringUtils.isNotBlank(params.getKey())){
            wrapper.and(w -> {
                w.like(DtoJob::getJobName, params.getKey())
                        .or()
                        .like(DtoJob::getCode, params.getKey())
                        .or()
                        .like(DtoJob::getRemark, params.getKey());
            });
        }

        wrapper.eq(ObjectUtils.isNotEmpty(params.getStatus()), DtoJob::getStatus, params.getStatus());


        // 添加 deptIds 查询条件
        if (params.getDeptIds() != null && !params.getDeptIds().isEmpty()) {
            for (Integer deptId : params.getDeptIds()) {
                wrapper.apply("JSON_CONTAINS(dept_ids, CAST({0} AS JSON))", deptId);
            }
        }
        return wrapper;
    }

    /**
     * 删除
     */
    @Override
    @Transactional
    public void deleteById(Integer id) {
        // 查询岗位有没有部门引用
        if (serviceUser.isExistByJobId(id)) {
            GraceException.display("当前岗位有员工无法删除");
        };
        removeById(id);
    }
    /**
     * 根据部门id查询岗位集合
     */
    @Override
    public List<DtoJob> listByDeptId(Integer deptId) {
        return baseMapper.listByDeptId(deptId);
    }

    /**
     * 保存
     */
    @Override
    @Transactional
    public void saveJob(DtoJob dtoJob) {
        final LambdaQueryWrapper<DtoJob> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(DtoJob::getId).last("LIMIT 1");
        final DtoJob job = getOne(wrapper);
        if (job == null) {
            dtoJob.setCode(UtilIdGenerator.generateId(JOB_CODE_PREFIX, JOB_CODE_LENGTH, CODE_START_VALUE));
        } else {
            dtoJob.setCode(UtilIdGenerator.incrementId(job.getCode()));
        }
        save(dtoJob);
    }
}